<template>
    <div class="box">
        <van-nav-bar
            title="订单核销"
            left-arrow
            @click-left="back()"
            right-text="帮助"
            :border="false"
            class="navBar"
        ></van-nav-bar>
        <van-search
            v-model="searchValue"
            show-action
            action-text="搜索"
            placeholder="请输入订单号"
            @click-right-icon="onScan"
            @search="onSearch"
        >
            <template #action>
                <div style="width: 1.87rem;">
                    <van-uploader
                        capture="camera"
                        :after-read="afterRead"
                        :show-upload="true"
                        ref="uploader"
                        style="position: absolute; right: 60px; z-index: 999;margin-top:.1875rem"
                    >
                        <van-icon name="scan" />
                    </van-uploader>
                    <div @click="onSearch" style="float: right">搜索</div>
                </div>
            </template>
        </van-search>
        <div class="container">
            <!-- 配件信息 -->
            <div class="cartsInfo">
                <!-- right-icon="scan" -->
                <van-cell-group>
                    <h4 class="title">客户信息</h4>
                    <van-cell
                        title="客户姓名："
                        :value="orderInfo.receiver"
                        value-class="cell-value"
                        title-class="title-class"
                        :border="false"
                    />
                    <van-cell
                        title="客户手机："
                        :value="orderInfo.tel"
                        value-class="cell-value"
                        :border="false"
                    />
                    <van-cell
                        title="订单编号："
                        :value="orderInfo.orderSn"
                        value-class="cell-value"
                    />
                    <van-cell
                        title="订单状态："
                        :value="orderStatusFilter[orderInfo.status/10]"
                        value-class="cell-value"
                    />
                    <!-- <van-cell
                        title="车牌号："
                        :value="orderInfo.detectionLicenseNum"
                        value-class="cell-value"
                    /> -->
                    <!-- <van-field
                        name="车牌号"
                        label="车牌号："
                        placeholder="请选择"
                        :rules="[{ required: true, message: '请填写车牌' }]"
                    />
                    <van-field
                        name="订单类型"
                        label="订单类型："
                        placeholder="请选择订单类型"
                        is-link
                        :rules="[{ required: true, message: '请选择订单类型' }]"
                    /> -->
                </van-cell-group>
                <!-- 测试单号：2021083114142828336585520026727 -->
                <!-- 测试套餐卡号：2021083117582566822622547064679    ID:167 -->
                <!-- piabjkStatus：0普通、1套餐卡 -->

                <!-- 普通订单明细 -->
                <div v-if="orderInfo.piabjkStatus == 0">
                    <!-- <h4 class="title">订单明细</h4> -->
                    <h4 class="title">商品信息</h4>
                    <van-cell-group
                        v-for="p in orderInfo.products"
                        v-bind:key="p.pid"
                    >
                        <van-cell
                            :title="p.name"
                            :value="p.num"
                            value-class="cell-value"
                            title-class="title-class"
                            :border="false"
                        />
                    </van-cell-group>
                    <h4 class="title">支付信息</h4>
                    <van-cell-group>
                        <van-cell
                            title="总金额:"
                            :value="orderInfo.price"
                            value-class="cell-value"
                            :border="false"
                        />
                        <van-cell
                            title="支付金额:"
                            :value="orderInfo.priceH"
                            value-class="cell-value"
                            :border="false"
                        />
                        <van-cell
                            title="下单时间:"
                            :value="orderInfo.addtime"
                            value-class="cell-value"
                            :border="false"
                        />
                    </van-cell-group>
                </div>
                <div v-else>
                    <!-- <h4 class="title">套餐卡明细</h4> -->
                    <table class="cancelList">
                        <thead>
                            <tr>
                            <th>项目名</th>
                            <th>可核销数量</th>
                            <th>已核销数量</th>
                            <th>数量单位</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                            <tr v-for="c in orderInfo.cancelList" v-bind:key="c.id">
                                <td width="26%">{{c.projectName}}</td>
                                <td width="17%">{{c.mayCancelNumber}}</td>
                                <td width="17%">{{c.alreadyCancelNumber}}</td>
                                <td width="20%">{{c.quantityUnit}}</td>
                                <td width="20%">
                                    <van-button v-show="c.mayCancelNumber>0" size="mini" type="danger" @click="cancelItem(c)">核销</van-button>
                                    <van-button v-show="c.mayCancelNumber<=0" size="mini" type="warn" disabled>已核销</van-button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    
                </div>
                <div style="margin: 16px" class="btn-wrap" v-show="orderInfo.piabjkStatus==0">
                    <van-button
                        block
                        color="#60328c"
                        native-type="submit"
                        :disabled="btnDisabled"
                        @click="cancel()"
                        >立即核销</van-button
                    >
                </div>
            </div>
        </div>

        <van-dialog v-model:show="showDialog" title="核销确认" show-cancel-button messageAlign="left" confirmButtonText="核销" @confirm="confirmCancel()">
            <div class="cancelDialog">
                <p style="text-align:left;">{{cancelInfo.projectName}}</p>
                <p style="text-align:left;">可核销数量：{{cancelInfo.mayCancelNumber}}</p>
                <p style="text-align:left;">核销数：<input type="number" style="width: 100px;border:1px solid #eee;" placeholder="单行输入" v-model="cancelInfo.cancelNumber">次</p>
            </div>
        </van-dialog>
    </div>
</template>
<script setup>
import QrCode from "qrcode-decoder";
import { BrowserMultiFormatReader } from "@zxing/library";
import jsQR from "jsqr";

import { onMounted, ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { orderList,piabjkProjectList,cancelAffirm } from "api/sales.js";
import { productCancel } from "api/order.js";
import { Dialog, Toast } from "vant";

const showDialog= ref(false)
const cancelInfo = ref({});
const btnDisabled = ref(true)
//1.未付款 2.待(提)收货 3.已完成 4.已关闭
const orderStatusFilter = [, "未付款", "待(提)收货", "已完成", "已关闭"];
const uploader = ref(null);
const searchValue = ref();
const orderInfo = ref({piabjkStatus:0});
const router = useRouter();
let codeReader = reactive(new BrowserMultiFormatReader());

//返回上一页
const back = () => {
    // router.back();
    router.push("/home");
};


let openScan = async () => {
    codeReader
        .listVideoInputDevices()
        .then((videoInputDevices) => {
            console.log("videoInputDevices", videoInputDevices, "摄像头设备");

            // 默认获取第一个摄像头设备id
            let firstDeviceId = videoInputDevices[0].deviceId; // 根据id选择摄像头

            decodeFromInputVideoFunc(firstDeviceId);
        })
        .catch((err) => {
            Toast.fail(err);
        });
};

let decodeFromInputVideoFunc = (firstDeviceId) => {
    codeReader.decodeFromInputVideoDeviceContinuously(
        null, // firstDeviceId  为null 时默认选择面向环境的摄像头
        "video",
        (result, err) => {
            if (result) {
                Toast.success(result + "扫描结果");
            }
            if (err && !err) {
                Toast.fail(err + "扫描失败");
            }
        }
    );
};

//搜索
const onSearch = async () => {
    //orderId:订单ID、orderSn:订单编号
    let params = { orderSn: searchValue.value,page:1,limit:200 };
    let res = await orderList(params);
    if (res.code == 300) {
        Toast.fail(res.msg);
        return;
    }
    if(res.data.length==0){
        orderInfo.value={piabjkStatus:0};
    }else{
        res.data[0].products = JSON.parse(res.data[0].products);
        orderInfo.value = res.data[0];

        if(orderInfo.value.piabjkStatus==1){
            //如果是套餐卡，则直接查询核销信息列表进行展示
            let res = await piabjkProjectList({
                orderId:orderInfo.value.orderId,
                page:1,
                limit:10
            })
            console.log("核销列表信息：",res.data)
            orderInfo.value['cancelList']=res.data;
        }else{
            console.log("零售信息：",orderInfo.value)
            //status为20：待提货/发货（核销按钮可点）
            if(orderInfo.value.status==20){
                btnDisabled.value=false;
            }else{
                btnDisabled.value=true;
            }
        }
    }
    console.log("搜索");
};

//扫描二维码
const onScan = () => {
    console.log(uploader.value);
    // uploader.value.chooseFile();
    console.log("调起摄像头");
    openScan();
};

const afterRead = (file) => {
    console.log("扫描结果准备处理");
    // Toast.success("扫描结果准备处理")
    getUrl(file.file);
};

function getUrl(file) {
    let url = getObjectURL(file);
    qrcode.decode(url);
    qrcode.callback = function (imgMsg) {
        console.log("reqrcode result:", imgMsg);
        console.log("订单号：", imgMsg);
        if (!imgMsg) {
            Toast.fail("识别失败");
            return;
        }
        searchValue.value = imgMsg;
        onSearch();
    };
}
function getObjectURL(file) {
    let url = null;
    if (window.createObjectURL !== undefined) {
        // basic
        url = window.createObjectURL(file);
    } else if (window.URL !== undefined) {
        // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL !== undefined) {
        // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

//核销零售订单
const cancel = () => {
    Dialog.confirm({
        title: '订单核销',
        message: '确定要核销此订单吗？',
    })
    .then(async() => {
        // on confirm
        console.log(orderInfo.value.orderSn);
        if(orderInfo.value.orderSn==""){
            Toast.fail("请填写订单号")
            return;
        }
        var formData = new URLSearchParams();
        formData.append("orderSn",orderInfo.value.orderSn);
        let res = await productCancel(formData);
        if (res.code == 0) {
            Toast.success(res.data);
            router.replace("/home");
        } else {
            Toast.fail(res.msg);
        }
    })
    .catch(() => {
        // on cancel
    });
};

//核销套餐卡小项目
const cancelItem =  (c) => {
    showDialog.value = true;
    cancelInfo.value=c;
    cancelInfo.value.cancelNumber=0;
}

const confirmCancel =async () => {
    console.log(cancelInfo.value.cancelNumber)
    if(cancelInfo.value.cancelNumber>cancelInfo.value.mayCancelNumber){
        Toast.fail("核销数量不能超过剩余次数")
        return;
    }
    if(cancelInfo.value.cancelNumber<1){
        Toast.fail("核销数量不能小于1")
        return;
    }
    let form = new URLSearchParams();
    form.append('id',cancelInfo.value.id)
    form.append('cancelNumber',cancelInfo.value.cancelNumber)
    let res = await cancelAffirm(form)
    console.log(res)
    if(res.code==0){
        Toast.success(res.data)
        let res2 = await piabjkProjectList({
            orderId:orderInfo.value.orderId,
            page:1,
            limit:10
        })
        console.log("核销列表信息：",res2.data)
        orderInfo.value['cancelList']=res2.data;
    }
}

</script>
<style scoped>
/* vite中深度选择器用  :deep , 不能使用  /deep/ 或  ::v-deep */
:deep .van-cell__value {
    text-align: left;
}
:deep .van-cell__title {
    width: 4.66rem;
    flex: initial !important;
}
:deep .van-field__label {
    margin-right: 0;
}
.cartsInfo {
    text-align: left;
}

.van-hairline--top-bottom::after,
.van-hairline-unset--top-bottom::after {
    border-width: 0;
}

/* 新的css */
/* 搜索圆角 */
.box :deep() .van-search__content {
    border-radius: 1rem;
}
/* 二维码颜色 */
.box :deep() .van-icon-scan {
    font-size: 1.25rem;
    color: #acb9c5;
}
/* 去掉vant 默认样式 */
.cartsInfo :deep() .van-cell-group {
    border-bottom: 1px solid #e5ebef;
    padding-bottom: 0.625rem;
}
.cartsInfo :deep() .van-cell-group:last-of-type {
    border: none;
}
.cartsInfo :deep() .van-cell {
    padding: 0.3125rem 0;
    align-items: center;
}
.cartsInfo :deep() .cell-value {
    text-align: right;
    color: #101d34;
}
.cartsInfo :deep() .van-cell__title {
    color: #49596d;
}
.cartsInfo :deep() .btn-wrap .van-button {
    border-radius: 1.375rem;
}
</style>

// 新增css
<style lang="scss" scoped src="../../styles/public.scss"></style>
<style lang="scss" scoped>
.cartsInfo {
    line-height: 1;
    background-color: #fff;
    padding: 0.625rem 0.9375rem;
    border-radius: 0.625rem;
    .title {
        margin: 1.25rem 0 0.625rem;
    }
    .cancelList{
        text-align: center;
        width: 100%;
        font-size: 13px;
        border: 1px solid #eee;
        color: #333;
        thead{
            height: 35px;
        }
        tbody{
            font-size: 12px;
        }
    }
}
.cancelDialog{
        padding-left: 30px;
    }
</style>